﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using PropertyChanged;
//using HKAY.DAL;
//using HKAY.Model;
//using MessageBox = HandyControl.Controls.MessageBox;
using SmartExporter;
using System.IO;
using Microsoft.Win32;
///using HKAY.Helper;
using System.Threading;
using System.Windows.Threading;
using Student = SmartExporter.Student;
using AllInOne.Entity;
using Newtonsoft.Json;
using AllInOne.EntityShowInfo;
using AllInOne.Common;
using System.Data;

namespace AllInOne.Menu
{
    /// <summary>
    /// Interaction logic for HistoryWindow.xaml
    /// </summary>
    [AddINotifyPropertyChangedInterface]
    public partial class RegisterInfoWindow : Window
    {        
        public string Product { get; set; }
        public string Sender { get; set; }
        public string Receiver { get; set; }
        private Timer m_timerToEnableButton;
        public List<RegisterInfo_ExcelOut> Records { get; set; }
        public int RecordSelectIndex { get; set; }

        public int MaterialSelectIndex { get; set; }

        public int UnitSelectIndex { get; set; }

        public DateTime Start { get; set; } = DateTime.Parse(DateTime.Today.ToString("yyyy-MM-dd") + " 00:00:00");
        public DateTime End { get; set; } = DateTime.Parse(DateTime.Today.ToString("yyyy-MM-dd") + " 23:59:59");

        public string Total { get; set; }
        public bool PrintBtnIsEnable { get; set; }

        public Visibility LoadingVisibility { get; set; } = Visibility.Collapsed;
        private delegate void DoPrintMethod(PrintDialog pdlg, DocumentPaginator paginator);

        public RegisterInfoWindow()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            SearchClick(null, null);
        }

        private void SearchClick(object sender, RoutedEventArgs e)
        {
            Task.Factory.StartNew(() =>
            {
                string msg = "";
                Dictionary<string, string> dic = new Dictionary<string, string>();
                //查询条件
                if (!string.IsNullOrEmpty(Product))
                {
                    dic.Add("GoodsName", Product);
                }
                if (!string.IsNullOrEmpty(Sender))
                {
                    dic.Add("Sender", Sender);
                }
                if (!string.IsNullOrEmpty(Receiver))
                {
                    dic.Add("Receiver", Receiver);
                }
                if (Start != null)
                {
                    dic.Add("ReceiveTimeStart", Start.ToString("yyyy-MM-dd HH:mm:ss"));
                }
                if (End != null)
                {
                    dic.Add("ReceiveTimeEnd", End.ToString("yyyy-MM-dd HH:mm:ss"));
                }

                var resultList = ServiceWebApi.QueryRegByParameter(dic, out msg);
                if (resultList == null || resultList.Count == 0)
                {
                    return;
                }
                string json = JsonConvert.SerializeObject(resultList);
                Records = JsonHelper.JSONStringToList<RegisterInfo_ExcelOut>(json);
                //for (int i = 0; i < Records.Count; i++)
                //{
                //    if (Records[i].GoodsName=="多种货物")
                //    {

                //    }
                //}
            });

        }

        private void Export(object sender, RoutedEventArgs e)
        {
            try
            {
                //将数据对象进行转换
                if (Records == null || Records.Count == 0)
                {
                    MessageAlert.Warning("数据为空,导出失败。");
                    return;
                }
                SaveFileDialog dlg = new SaveFileDialog();
                dlg.Title = "保存文件";
                dlg.FileName = $"{DateTime.Now:yyyy-MM-dd}导出数据.xls"; // Default file name
                dlg.DefaultExt = ".xls"; // Default file extension
                dlg.Filter = "Excel documents|*.xls";
                if (dlg.ShowDialog() == true)
                {
                    LoadingVisibility = Visibility.Visible;
                    DataTable dtTemp = DealFormatData(Records);
                    if (ExportExcelHelper.ToExcel(dlg.FileName, dtTemp))
                    {
                        MessageBox.Show("导出成功。", "成功", MessageBoxButton.OK, MessageBoxImage.Information);
                    }
                    else
                    {
                        MessageAlert.Warning("导出失败。");
                        SimpleConsole.WriteInfo("门卫数据展示-导出Excel异常", this);
                    }
                }
            }
            catch (Exception ex)
            {
                SimpleConsole.WriteInfo("门卫数据展示-导出Excel异常" + ex.ToString(), this);
                MessageAlert.Error("导出失败。");
            }
            LoadingVisibility = Visibility.Collapsed;
        }

        readonly string DateTimeFormat="M月d日HH时mm分";

        public DataTable DealFormatData(List<RegisterInfo_ExcelOut> tempRecords)
        {
            DataTable dtTemp = new DataTable();
            try
            {
                dtTemp.Columns.Add("xu_hao", typeof(string));
                dtTemp.Columns.Add("xing_ming", typeof(string));
                dtTemp.Columns.Add("xing_bie", typeof(string));
                dtTemp.Columns.Add("nian_ling", typeof(string));
                dtTemp.Columns.Add("che_hao", typeof(string));
                dtTemp.Columns.Add("huo_wu", typeof(string));
                dtTemp.Columns.Add("di_zhi", typeof(string));
                dtTemp.Columns.Add("lian_xi_dian_hua", typeof(string));
                dtTemp.Columns.Add("jin_chang_shi_jian", typeof(string));
                dtTemp.Columns.Add("ti_wen", typeof(string));
                dtTemp.Columns.Add("jin_shi_si_tian", typeof(string));
                dtTemp.Columns.Add("shen_fen_zheng_hao", typeof(string));
                dtTemp.Columns.Add("chu_chang_shi_jian", typeof(string));               
                for (int i = 0; i < tempRecords.Count; i++)
                {
                    DataRow dr = dtTemp.NewRow();
                    dr["xu_hao"] = (i + 1).ToString();
                    dr["xing_ming"] = tempRecords[i].RegName;
                    dr["xing_bie"] = Convert.ToBoolean(int.Parse(tempRecords[i].IdentityNum.Substring(16, 1)) % 2) ? "男" : "女";
                    dr["nian_ling"] = JudgeAge(tempRecords[i].IdentityNum);
                    dr["che_hao"] = tempRecords[i].Plate;
                    dr["huo_wu"] = tempRecords[i].GoodsName;
                    dr["di_zhi"] = tempRecords[i].Value3;
                    dr["lian_xi_dian_hua"] = tempRecords[i].RegPhone;
                    dr["jin_chang_shi_jian"] = tempRecords[i].ReceiveTime.ToString(DateTimeFormat);
                    dr["ti_wen"] = tempRecords[i].RegName;
                    dr["jin_shi_si_tian"] = tempRecords[i].RegName;//近十四天
                    dr["shen_fen_zheng_hao"] = tempRecords[i].IdentityNum;
                    if (tempRecords[i].ReturnTime != null)
                    {
                        try
                        {
                            dr["chu_chang_shi_jian"] = tempRecords[i].ReturnTime.ToString(DateTimeFormat);
                            if (dr["chu_chang_shi_jian"].ToString()== "1月1日00时00分")
                            {
                                dr["chu_chang_shi_jian"] = "";
                            }
                        }
                        catch
                        {
                        }
                    }
                    dtTemp.Rows.Add(dr);
                }
            }
            catch (Exception ex)
            {
            }
            return dtTemp;
        }

        public int JudgeAge(string idCard)
        {
            int age = 0;
            var subStr = string.Empty;
            if (idCard.Length == 18)
            {
                subStr = idCard.Substring(6, 8).Insert(4, "-").Insert(7, "-");
            }
            else if (idCard.Length == 15)
            {
                subStr = ("19" + idCard.Substring(6, 6)).Insert(4, "-").Insert(7, "-");
            }
            TimeSpan ts = DateTime.Now.Subtract(Convert.ToDateTime(subStr));
            return age = ts.Days / 365;
        }

        /// <summary>
        /// 弃用，因为有几个线程，以及其他的问题，不好修改，所以不使用
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Export_2(object sender, RoutedEventArgs e)
        {
            try
            {
                //将数据对象进行转换
                if (Records == null || Records.Count == 0)
                {
                    MessageAlert.Warning("数据为空,导出失败。");
                    return;
                }
                SaveFileDialog dlg = new SaveFileDialog();
                dlg.Title = "保存文件";
                dlg.FileName = $"{DateTime.Now:yyyy-MM-dd}导出数据.xls"; // Default file name
                dlg.DefaultExt = ".xls"; // Default file extension
                dlg.Filter = "Excel documents|*.xls"; // Filter files by extension
                                                      //dlg.InitialDirectory = initFolder;
                                                      // Process save file dialog box results
                if (dlg.ShowDialog() == true)
                {
                    LoadingVisibility = Visibility.Visible;
                    ExportUtil util = new ExportUtil();
                    util.ProgressCompleted += (a, ex) =>
                    {
                        LoadingVisibility = Visibility.Collapsed;
                        if (!a)
                        {
                            MessageAlert.Warning("导出失败。");
                            SimpleConsole.WriteInfo("门卫数据展示-导出Excel异常" + ex.ToString(), this);
                        }
                        else
                        {
                            MessageBox.Show("导出成功。", "成功", MessageBoxButton.OK, MessageBoxImage.Information);
                        }
                    };
                    util.ExportAsync(dlg.FileName, Records, Records.Count);
                }
            }
            catch (Exception ex)
            {
                SimpleConsole.WriteInfo("门卫数据展示-导出Excel异常" + ex.ToString(), this);
                MessageAlert.Error("导出失败。");
            }
        }
        private void Detial(object sender, RoutedEventArgs e)
        {
            //T_RegisterInfo t_RegisterInfo = new T_RegisterInfo();
            //t_RegisterInfo = Records[RecordSelectIndex];
        }

    }
}
